package cn.kgc.controller;
import cn.kgc.commons.annoation.DictLog;
import cn.kgc.commons.constant.LogTypeEnum;
import cn.kgc.commons.constant.ModuleName;
import cn.kgc.commons.constant.OperateType;
import cn.kgc.commons.constant.SystemConstant;
import cn.kgc.commons.exception.HttpException;
import cn.kgc.commons.util.UpdateGroup;
import cn.kgc.dto.PmsBrandDTO;
import cn.kgc.entity.PmsCategory;
import cn.kgc.entity.PmsCategoryBrandRelation;
import cn.kgc.service.PmsCategoryBrandRelationService;
import cn.kgc.service.PmsCategoryService;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.kgc.entity.PmsBrand;
import cn.kgc.dto.PmsBrandAddDTO;
import cn.kgc.dto.PmsBrandUpdateDTO;
import cn.kgc.service.PmsBrandService;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import cn.kgc.commons.vo.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import cn.kgc.entity.PmsBrand;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * 品牌(PmsBrand)表控制层
 *
 * @author makejava
 * @since 2022-11-27 13:41:20
 */
@RestController
@RequestMapping("pms/brand")
@Api(tags = "品牌表")
@Validated
@Slf4j
public class PmsBrandController {
    /**
     * 服务对象
     */
    @Resource
    private PmsBrandService pmsBrandService;
    @Resource
    private PmsCategoryService pmsCategoryService;
    @Resource
    private PmsCategoryBrandRelationService pmsCategoryBrandRelationService;

    /**
     *  根据商品的分类的id查询品牌的信息
     */
    @GetMapping("listByCategoryId")
    @ApiOperation(value = "根据分类id查询请求", produces = "application/json;charset=utf-8",
            httpMethod = "GET", response = Result.class)
    @CrossOrigin
    @ApiImplicitParam(name = "categoryId", value = "分类id", paramType = "query", dataType = "int")
    public List<PmsBrand> selectPmsBrandByCategoryId(Long categoryId){
        LambdaQueryWrapper<PmsCategoryBrandRelation> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PmsCategoryBrandRelation::getCatelogId,categoryId);
        List<PmsCategoryBrandRelation> pmsCategoryBrandRelations=pmsCategoryBrandRelationService.list(lambdaQueryWrapper);
        List<PmsBrand> pmsBrands=new ArrayList<>();
        if (CollectionUtils.isEmpty(pmsCategoryBrandRelations)){
            return pmsBrands;
        }
        pmsCategoryBrandRelations.forEach(pmsCategoryBrandRelation -> {
            PmsBrand pmsBrand=pmsBrandService.getById(pmsCategoryBrandRelation.getBrandId());
            pmsBrands.add(pmsBrand);
        });
        return pmsBrands;
    }

    /**
     * 分页查询所有数据
     *
     * @param current 分页对象
     * @return 所有数据
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询所有数据", produces = "application/json;charset=utf-8",
            httpMethod = "GET", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页个数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "firstLetter", value = "品牌首字母", paramType = "query", dataType = "string")
    })
    @DictLog(logType = LogTypeEnum.COMMON_OPERATE,moduleName = ModuleName.MODULE_NAME_PMS,logContent = "查询品牌信息",operateType = OperateType.SELECT)
    @CrossOrigin
    public IPage<PmsBrand> page(@RequestParam(defaultValue = "1") int current,
                                @RequestParam(defaultValue = "5") int pageSize,
                                @RequestParam(name = "firstLetter",defaultValue = "") String firstLetter) {
        log.info("分页查询品牌信息:当前页是:{},每页个数是:{},品牌首字母是:{}", current, pageSize, firstLetter);
        IPage<PmsBrand> page = new Page(current, pageSize);
        LambdaQueryWrapper<PmsBrand> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(firstLetter)){
            lambdaQueryWrapper.eq(PmsBrand::getFirstLetter,firstLetter);
        }
        lambdaQueryWrapper.orderByDesc(PmsBrand::getSort);
        return pmsBrandService.page(page,lambdaQueryWrapper);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    @CrossOrigin
    @ApiOperation(value = "通过主键查询单条数据", produces = "application/json;charset=utf-8",
            httpMethod = "GET", response = Result.class)
    @ApiImplicitParam(name = "id", value = "主键", paramType = "path", dataType = "int")
    @Cacheable(value = "pmsbrand", key = "#root.method.name+#id")
    public PmsBrand selectOne(@PathVariable Serializable id) {
        return this.pmsBrandService.getById(id);
    }

    /**
     * 新增数据
     *
     * @param pmsBrandDTO 实体对象
     * @return 新增结果
     */
    @PostMapping("/insert")
    @ApiOperation(value = "新增", produces = "application/json;charset=utf-8",
            httpMethod = "POST", response = Result.class)
    @CrossOrigin
    public boolean insert(@Validated @RequestBody PmsBrandAddDTO pmsBrandDTO) {
        log.info("新增品牌信息:{}", pmsBrandDTO);
        return pmsBrandService.saveBrandAndRelation(pmsBrandDTO);
    }

    /**
     * 修改数据
     *
     * @param pmsBrandDTO 实体对象
     * @return 修改结果
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改信息", produces = "application/json;charset=utf-8",
            httpMethod = "POST", response = Result.class)
    @CrossOrigin
    @Caching(evict = {
            @CacheEvict(value = "pmsbrand",key = "'selectOne'+#pmsBrandDTO.id")
    })
    public boolean update(@Validated @RequestBody PmsBrandUpdateDTO pmsBrandDTO) {
        //categoryId分类ID的集合，集合中几个分类存在的  集合中的分类都存在 集合中的分类都不存在
        List<Long> categoryIds = pmsBrandDTO.getCategoryIds();
        for (Long categoryId : categoryIds) {
            PmsCategory pmsCategory = pmsCategoryService.getById(categoryId);
            if (pmsCategory==null){
                throw new HttpException(20002,500);
            }
        }
        return this.pmsBrandService.updateBrandAndRelation(pmsBrandDTO);
    }


    @PostMapping("/update2")
    @ApiOperation(value = "修改信息(新增和修改的参数是同一个参数)", produces = "application/json;charset=utf-8",
            httpMethod = "POST", response = Result.class)
    @CrossOrigin
    @Caching(evict = {
            @CacheEvict(value = "pmsbrand",key = "'selectOne'+#pmsBrandDTO.id")
    })
    public boolean update2(@Validated(value = UpdateGroup.class) @RequestBody PmsBrandDTO pmsBrandDTO) {
        PmsBrand pmsBrand = this.pmsBrandService.getById(pmsBrandDTO.getId());
        BeanUtils.copyProperties(pmsBrandDTO, pmsBrand);
        return this.pmsBrandService.updateById(pmsBrand);
    }
    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除结果
     */
    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "根据主键删除信息", produces = "application/json;charset=utf-8",
            httpMethod = "DELETE", response = Result.class)
    @ApiImplicitParam(name = "id", value = "主键", paramType = "path", dataType = "int")
    @CrossOrigin
    public boolean delete(@PathVariable Long id) {
        return this.pmsBrandService.deleteBrandAndRelation(id);
    }
}
